<template>
  <div class="app-container">
    <br />
    <!--条件筛选区-->
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="70px"
      class="condition_form">
      <el-row>
        <el-col :span="5.5">
          <!--根据用户名模糊查询-->
          <el-form-item label="用户名" prop="username">
            <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <!--根据账号状态精确匹配-->
          <el-form-item label="账号状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 100px;">
              <el-option :key="'0'" label="正常" :value="'0'" />
              <el-option :key="'1'" label="封禁" :value="'1'" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="注册时间">
            <el-date-picker v-model="queryParams.startTime" type="datetime" placeholder="选择注册开始时间" align="right"
              style="width: 200px;" :picker-options="pickerOptions" value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
            -
            <el-date-picker v-model="queryParams.endTime" type="datetime" placeholder="选择注册结束时间" align="right"
              value-format="yyyy-MM-dd HH:mm:ss" style="width: 200px;" :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item class="serch-button">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>


    </el-form>
    <el-divider></el-divider>

    <!--增删操作区-->
    <el-row style="float: right; margin-bottom: 20px">

      <el-col :span="12">
        <el-button type="primary" plain icon="el-icon-circle-plus-outline" @click="handleAdd"
          style="margin-right: 30px">
          新增用户
        </el-button>
      </el-col>

      <el-col :span="12">
        <el-button type="danger" plain icon="el-icon-delete" :disabled="multiple" @click="handleDelete">
          批量删除
        </el-button>
      </el-col>
    </el-row>


    <!--数据展示区-->
    <el-table v-loading="loading" :data="userList" border stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="60px" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="头像" align="center" prop="avatar" type="img">
        <template slot-scope="scope">
          <el-image style="height: 80px;width: 80px" :src="scope.row.avatar" />
        </template>
      </el-table-column>
      <el-table-column prop="gender" label="性别" align="center" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.gender == 0">男</span>
          <span v-if="scope.row.gender == 1">女</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="账号状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 0" type="success">正常</el-tag>
          <el-tag v-if="scope.row.status == 1" type="danger">封禁</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="生日" align="center" prop="birthday" />
      <el-table-column label="注册时间" align="center" prop="registerTime" />

      <!-- <el-table-column prop="roleId" label="角色" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.roleId == 1" type="success">管理员</el-tag>
          <el-tag v-if="scope.row.roleId == 2" type="danger">普通用户</el-tag>
        </template>
      </el-table-column> -->


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button v-if="scope.row.status == 1" type="text" icon="el-icon-success"
            @click="handleChangeStatus(scope.row, '0')">解封账号</el-button>
          <el-button v-if="scope.row.status == 0" type="text" icon="el-icon-error"
            @click="handleChangeStatus(scope.row, '1')">封禁账号</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-divider></el-divider>

    <!--页数-->
    <el-pagination :page-size.sync="queryParams.pageSize" layout="total, sizes, prev, pager, next, jumper"
      :total="total" :page-sizes="[5,10, 20, 30, 40]" :current-page.sync="queryParams.pageNum" @current-change="getList"
      @size-change="getList" />

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="头像" prop="avatar">
          <el-upload class="avatar-uploader" name="img" :action="uploadURL" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="token">
            <img :src="form.avatar?form.avatar:'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png'"
              class="avatar">
            <div style="font-size:xx-small;">点击上传头像，只能上传jpg/png文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item v-if="addOrUpdate" label="密码" prop="password">
          <el-input v-if="addOrUpdate" type="password" v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="addOrUpdate" label="确认密码" prop="checkPass">
          <el-input v-if="addOrUpdate" type="password" v-model="form.checkPass" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="电话号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话号" />
        </el-form-item>
        <el-form-item label="用户性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择">
            <el-option :key="'0'" label="男" :value="'0'" />
            <el-option :key="'1'" label="女" :value="'1'" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option :key="0" label="正常" :value="0" />
            <el-option :key="1" label="封禁" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户生日">
          <el-date-picker type="date" placeholder="选择日期" v-model="form.birthday" style="width: 100%;"
            format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {getPageUser, changeUserStatus, deleteUser, getUserInfoById, updateUserInfo,addUser} from '@/api/user';

export default {
  name: 'User',
  data() {
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.form.checkPass !== '') {
          this.$refs.form.validateField('checkPass');
        }
        callback();
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      //密码校验
      rules: {
        password: [
          {validator: validatePass, trigger: 'blur'}
        ],
        checkPass: [
          {validator: validatePass2, trigger: 'blur'}
        ],
      },
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      //上传地址
      uploadURL: 'http://localhost:3315/admin/upload',
      // uploadURL: 'http://localhost:9999/upload',
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        //当前页数
        pageNum: 1,
        //每页大小
        pageSize: 5,
        //用户名
        username: '',
        //账号状态
        status: '',
        //注册时间
        startTime: '',
        endTime: '',
      },
      // 表单参数
      form: {},
      token: {
        token: ''
      },
      //判断新增修改表单
      addOrUpdate: false
    }
  },
  created() {
    this.getList()
    this.token.token = this.$store.getters.token
  },
  methods: {
    /**
     * 新增用户
     */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加用户'
      this.addOrUpdate = true
    },
    /**
     * 修改按钮操作
     * @param row
     */
    handleUpdate(row) {
      this.reset()
      getUserInfoById(row.id).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改用户'
        this.addOrUpdate = false
      })
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      getPageUser(this.queryParams).then((response) => {
        this.userList = response.data.list;
        this.total = response.data.total;
        this.loading = false
      })
    },
    handleChangeStatus(user, newStatus) {
      //解封
      if (newStatus == '0') {
        this.$confirm('此操作将解封账号ID为' + user.id + '的用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //修改用户状态核心
          this.loading = true
          changeUserStatus(user.id, newStatus).then((response) => {
            this.$notify({
              title: '操作成功',
              message: '解除封禁账号成功',
              type: 'success'
            });
            this.open = false
            this.getList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消解除封禁账号操作'
          });
        });
      }
      //封禁
      else {
        this.$confirm('此操作将封禁账号ID为' + user.id + '的用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //修改用户状态核心
          this.loading = true
          changeUserStatus(user.id, newStatus).then((response) => {
            this.$notify({
              title: '操作成功',
              message: '封禁账号成功！',
              type: 'success'
            });
            this.open = false
            this.getList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消封禁账号操作'
          });
        });
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.queryParams = {
        //当前页数
        pageNum: 1,
        //每页大小
        pageSize: 5,
        //用户名
        username: '',
        //账号状态
        status: '',
        //注册时间
        startTime: '',
        endTime: '',
      }
      this.form = {}
      this.getList()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateUserInfo(this.form).then((response) => {
              this.$notify({
                title: '操作成功',
                message: '修改用户成功！',
                type: 'success'
              });
              this.open = false
              this.getList()
            })
          } else {
            addUser(this.form).then((response) => {
              this.$notify({
                title: '操作成功',
                message: '新增用户成功！',
                type: 'success'
              });
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$alert('是否确认删除用户编号为"' + ids + '"的数据项？', '提示', {
        confirmButtonText: '确定',
        callback: action => {
          return deleteUser(ids).then(() => {
            this.getList()
            this.$notify({
              title: '操作成功',
              message: '删除用户成功！',
              type: 'success'
            });
          })
        }
      })
    },
    // 图片上传成功回调
    handleAvatarSuccess(res) {//上传封面
      if (res.code === 200) {
        this.form.avatar = res.data
        this.$notify({
          title: '操作成功',
          message: '图书封面上传成功',
          type: 'success'
        })
      } else {
        this.$notify.error({
          title: '操作失败',
          message: '图书封面上传失败，请稍后重试！'
        })
      }
    },
    beforeAvatarUpload(file) {//判断头像大小
      const isJPG = file.type == 'image/png' || file.type == 'image/jpg' || file.type == 'image/jpeg';
      //file.size / 1024 / 1024 表示将文件大小从字节转换为MB。< 10 表示判断文件大小是否小于10MB
      const isLt2M = file.size / 1024 / 1024 < 10;
      // console.log(file);
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/JPEG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isJPG && isLt2M;
    },
  }
}
</script>

<style scoped>
.condition_form .el-form-item__label {
  font-size: 14px;
}

.app-container {
  margin: 20px;
}

.avatar {
  margin-left: 100px;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  display: block;
  object-fit: cover;
}
</style>
